package com.adnaan.backend.controller.wechat;

import cn.dev33.satoken.stp.StpUtil;
import com.adnaan.backend.common.annotation.RestControllerMapping;
import com.adnaan.backend.common.model.PageParams;
import com.adnaan.backend.common.model.Result;
import com.adnaan.backend.entity.Article;
import com.adnaan.backend.entity.ArticleTags;
import com.adnaan.backend.entity.dto.OptionDto;
import com.adnaan.backend.entity.vo.CommentVo;
import com.adnaan.backend.entity.vo.ViewHistoryVo;
import com.adnaan.backend.service.ArticleService;
import com.adnaan.backend.service.ArticleTagsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * author: adnaan
 * create: 2025-02-23 13:11
 * Description:
 */
@Tag(name = "小程序文章数据", description = "小程序文章数据")
@RestControllerMapping("/wx-article")
public class WxArticleController {

    @Resource
    private ArticleService articleService;

    @Resource
    private ArticleTagsService articleTagsService;

    /**
     * 获取标签
     */
    @GetMapping("/tags")
    @ApiOperationSupport(order = 0)
    @Operation(summary = "获取标签")
    public Result<List<OptionDto>> getTags() {
        List<ArticleTags> list = articleTagsService.list();
        List<OptionDto> optionDtos = list.stream().map(item -> {
            OptionDto optionDto = new OptionDto();
            optionDto.setLabel(item.getTagName());
            optionDto.setValue(String.valueOf(item.getId()));
            return optionDto;
        }).toList();
        return Result.success(optionDtos);
    }

    @PostMapping("/page")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "文章分页查询")
    public Result<Page<Article>> pageQuery(@RequestBody PageParams<Article> pageParams) {
        // 1.查询参数
        Article params = pageParams.getParams();
        LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper<>();
        // 2.查询条件 标题 标签（多选) 排序
        lqw.like(params.getTitle() != null, Article::getTitle, params.getTitle());
        // 标签筛选
        if (params.getTagIds() != null && !params.getTagIds().isEmpty()) {
            List<Long> articleIds = articleService.getArticleIdsByTagIds(params.getTagIds());
            lqw.in(articleIds != null && !articleIds.isEmpty(), Article::getId, articleIds);
        }
        lqw.orderByDesc(Article::getCreateTime);
        // 3.分页查询
        Page<Article> page = articleService.page(pageParams.getPage(), lqw);
        page.getRecords().forEach(item -> {
            item.setTags(articleService.getTags(item.getId()));
            item.setCollectCount(articleService.getCollectCount(item.getId()));
        });
        return Result.success(page);
    }

    /**
     * 获取文章详情
     *
     * @param id 文章id
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "获取文章详情")
    public Result<Article> getDetail(@RequestParam String id) {
        Long userId = StpUtil.getLoginIdAsLong();
        Article article = articleService.getById(id);
        article.setTags(articleService.getTags(article.getId()));
        article.setLikeCount(articleService.getLikeCount(article.getId()));
        article.setLiked(articleService.isArticleLiked(userId, article.getId()));
        article.setCollected(articleService.isArticleCollected(userId, article.getId()));
        article.setComments(articleService.getCommentsByArticleId(article.getId()));
        article.setProcess(articleService.getProcess(article.getId()));
        //增加浏览量
        articleService.increasePageView(article.getId());
        return Result.success(article);
    }

    /**
     * 记录用户阅读历史
     */
    @PostMapping("/read-history")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "记录用户阅读历史")
    public Result<Boolean> readHistory(@RequestBody ViewHistoryVo viewHistoryVo) {
        if (articleService.readHistory(viewHistoryVo)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 用户点赞
     *
     * @param articleId 文章id
     */
    @GetMapping("/like")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "用户点赞")
    public Result<Boolean> likeArticle(@RequestParam Long articleId) {
        Long userId = StpUtil.getLoginIdAsLong();
        articleService.likeArticle(userId, articleId);
        return Result.success();
    }

    /**
     * 用户收藏
     *
     * @param articleId 文章id
     */
    @GetMapping("/collect")
    @ApiOperationSupport(order = 7)
    @Operation(summary = "用户收藏")
    public Result<Boolean> collectArticle(@RequestParam Long articleId) {
        Long userId = StpUtil.getLoginIdAsLong();
        articleService.collectArticle(userId, articleId);
        return Result.success();
    }

    /**
     * 添加评论
     *
     * @param commentVo 评论实体
     */
    @PostMapping("/comment")
    @ApiOperationSupport(order = 10)
    @Operation(summary = "添加评论")
    public Result<Boolean> addComment(@RequestBody CommentVo commentVo) {
        Long userId = StpUtil.getLoginIdAsLong();
        articleService.addComment(userId, commentVo.getArticleId(), commentVo.getCommentContent());
        return Result.success();
    }
}
